﻿@page "/consolelog/{SimNumber}"
@using System.Threading.Channels
@using JT808Protocol.Methods
@using JT808Protocol.Models
@using System.Globalization
@using Console = BootstrapBlazor.Components.Console
@inject JT808Parser parser;
@inject Channel<JT808Package> channel

<div>
    <Console Items="Messages" Height="450" LightTitle="" HeaderText="" ShowAutoScroll="true" OnClear="@(()=> Messages.Clear())"></Console>
</div>

@code {
    [Parameter]
    public string SimNumber { get; set; }

    private List<ConsoleMessageItem> Messages;

    protected override Task OnInitializedAsync()
    {
        Messages = new List<ConsoleMessageItem>();

        //实时刷新数据
        Task.Run(async () => {
            while (await channel.Reader.WaitToReadAsync())
            {
                var package =  await channel.Reader.ReadAsync();

                if (package.Header.SimNumber != SimNumber)
                {
                    await channel.Writer.WriteAsync(package);
                    continue;
                }
                Messages.Add(new ConsoleMessageItem
                {
                    Message = $"{DateTimeOffset.Now.ToString("F")} {package.ReadBodyString()}"
                });

                //通知页面变量改变
                await InvokeAsync(() =>
                {
                    this.StateHasChanged();
                });
             }
        });   

        return base.OnInitializedAsync();
    }
}
